#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct singleton {
    char name[32];
    void (*show)(struct singleton *s);
} Singleton;

void singleton_show(struct singleton *s)
{
    printf("singleton show, name:%s\n", s->name);
}

pthread_mutex_t g_mutex;

Singleton *destroy_singleton(Singleton *s)
{
    if (s != NULL) {
        free(s);
    }
    return NULL;
}

Singleton *create_singleton(const char *name)
{
    static Singleton *singleton_inst = {0};
    if (singleton_inst != NULL) {
        return singleton_inst;
    }

    pthread_mutex_lock(&g_mutex);

    if (singleton_inst != NULL) {
        pthread_mutex_unlock(&g_mutex);
        return singleton_inst;
    }

    singleton_inst = (Singleton *)malloc(sizeof(Singleton));
    memset(singleton_inst, 0, sizeof(Singleton));
    singleton_inst->show = singleton_show;
    strcpy(singleton_inst->name, name);
    printf("create inst success, name:%s ,ptr:%p\n", singleton_inst->name,
           singleton_inst);

    pthread_mutex_unlock(&g_mutex);

    return singleton_inst;
}

int main()
{
    Singleton *inst = NULL;
    char *     name = "john";
    int        i    = 0;

    for (i = 0; i < 10; i++) {
        inst = create_singleton(name);
        printf("[%02d]create inst, ptr:%p\n", i, inst);
    }

    inst = destroy_singleton(inst);
    return 0;
}
